package com.apes.scm.masterdata.stock.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.stock.model.DcDistributionRange;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.DcDistributionRangeRepository;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apestech.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("dcDistributionRangeService")
public class DcDistributionRangeService extends DomainService {
    @Autowired
    private DcDistributionRangeRepository dcDistributionRangeRepository;

    public DcDistributionRange save(SimpleRequest request) {
        DcDistributionRange dcDistributionRange = request.getO(DcDistributionRange.class);
        this.judgeWeights(dcDistributionRange.getFLocationId().getId(), dcDistributionRange.getCLocationId(), dcDistributionRange.getOnlineWeights(), dcDistributionRange.getOfflineWeights(), dcDistributionRange.getSafetyStockMark(), "");
        return dcDistributionRangeRepository.saveAndFlush(dcDistributionRange);
    }

    public DcDistributionRange update(SimpleRequest request) {
        DcDistributionRange dcDistributionRange = request.getO(DcDistributionRange.class);
        this.judgeWeights(dcDistributionRange.getFLocationId().getId(), dcDistributionRange.getCLocationId(), dcDistributionRange.getOnlineWeights(), dcDistributionRange.getOfflineWeights(), dcDistributionRange.getSafetyStockMark(), dcDistributionRange.getId());
        return dcDistributionRangeRepository.saveAndFlush(dcDistributionRange);
    }

    public String delete(SimpleRequest request) {
        DcDistributionRange dcDistributionRange = request.getO(DcDistributionRange.class);
        dcDistributionRangeRepository.delete(dcDistributionRange.getId());
        return "删除成功";
    }

    /**
     * 重复数据判断
     * @param flocationId
     * @param clocationId
     * @param onLineweights
     * @param offlineWeights
     * @param id
     */
    private void judgeWeights(String flocationId, Location clocationId, int onLineweights, int offlineWeights, int safetyStockMark, String id) {
        String sql = "SELECT * FROM MAS_DC_DISTRIBUTION_RANGE WHERE F_LOCATION_ID = '" + flocationId + "' AND C_LOCATION_ID = '" + clocationId.getId() + "'" ;
        if (!StringUtil.isEmpty(id)) sql += " AND ID != '" + id + "'";
        List distinctDatas = dcDistributionRangeRepository.findAll(sql);
        if (distinctDatas.size() != 0) throw new RuntimeException(String.format("子仓库 [%s] 已配置该父仓库范围, 请查询核实！", clocationId.getName()));

        sql = "SELECT * FROM MAS_DC_DISTRIBUTION_RANGE WHERE C_LOCATION_ID = '" + clocationId.getId() + "' AND ONLINE_WEIGHTS = " + onLineweights;
        if (!StringUtil.isEmpty(id)) sql += " AND ID != '" + id + "'";
        List judgeWeights = dcDistributionRangeRepository.findAll(sql);
        if (judgeWeights.size() > 0) throw new RuntimeException(String.format("子仓库 [%s] 线上要货权重已存在！", clocationId.getName()));

        sql = "SELECT * FROM MAS_DC_DISTRIBUTION_RANGE WHERE C_LOCATION_ID = '" + clocationId.getId() + "' AND OFFLINE_WEIGHTS = " + offlineWeights;
        if (!StringUtil.isEmpty(id)) sql += " AND ID != '" + id + "'";
        judgeWeights = dcDistributionRangeRepository.findAll(sql);
        if (judgeWeights.size() > 0) throw new RuntimeException(String.format("子仓库 [%s] 线下要货权重已存在！", clocationId.getName()));

        sql = "SELECT * FROM MAS_DC_DISTRIBUTION_RANGE WHERE SAFETY_STOCK_MARK != 0 AND C_LOCATION_ID = '" + clocationId.getId() + "' AND SAFETY_STOCK_MARK = " + safetyStockMark;
        if (!StringUtil.isEmpty(id)) sql += " AND ID != '" + id + "'";
        judgeWeights = dcDistributionRangeRepository.findAll(sql);
        if (judgeWeights.size() > 0) throw new RuntimeException(String.format("子仓库 [%s] 安全库存配货权重已存在！", clocationId.getName()));

    /*    Location location = SpringManager.getBean(LocationRepository.class).findOne(flocationId);
        sql = "" +
                "SELECT C.DEPOT_LEVEL, COUNT(*) " +
                "  FROM MAS_DC_DISTRIBUTION_RANGE A, MAS_LOCATION B, MAS_DEPOT C " +
                " WHERE A.F_LOCATION_ID = B.ID " +
                "   AND B.DEPOT_ID = C.ID AND C.DEPOT_LEVEL = '" + location.getDepot().getDepotLevel().getId() + "' " +
                "   AND A.C_LOCATION_ID = '" + clocationId.getId() + "'";
        if (!StringUtil.isEmpty(id)) sql += " AND A.ID != '" + id + "'";
        sql += " GROUP BY C.DEPOT_LEVEL ";
        List judgeDepotLevels = dcDistributionRangeRepository.findAll(sql);
        if (judgeDepotLevels.size() > 0) throw new RuntimeException("安全库存配货标记不能配置有多个相同仓库类别的父仓库，请核实!");*/

        if (safetyStockMark == 0) return;
        Location location = SpringManager.getBean(LocationRepository.class).findOne(flocationId);
        sql = " SELECT COUNT(*), B.COMPANY_ID, A.C_LOCATION_ID " +
                "  FROM MAS_DC_DISTRIBUTION_RANGE A, MAS_LOCATION B " +
                " WHERE A.F_LOCATION_ID = B.ID " +
                "   AND A.C_LOCATION_ID = '"+ clocationId.getId() +"' " +
                "   AND B.COMPANY_ID = '"+ location.getCompany().getId() + "' " +
                "   AND SAFETY_STOCK_MARK != 0 ";

        if (!StringUtil.isEmpty(id)) sql += " AND A.ID != '" + id + "'";
        sql += " GROUP BY B.COMPANY_ID, A.C_LOCATION_ID ";
        List sameCompanyLocation = dcDistributionRangeRepository.findAll(sql);
        if (sameCompanyLocation.size() > 0) throw new RuntimeException("已设置有相同公司的父仓库，同公司的父仓库只能配置一个安全库存配货，请核实!");

    }
	
	public Object findAllToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        Date timestamp = null;
        int maxNum = jsonObject.getInteger("maxNum"); //单次请求最大条数
        String id = jsonObject.getString("id");
        if (jsonObject.get("timestamp") == null || jsonObject.get("maxNum") == null) {
            throw new RuntimeException("传入参数时间和本次请求最大值参数确实，请检查！");
        }
        try {
            timestamp = new Date(jsonObject.getLong("timestamp"));
        } catch (Exception e) {
            throw new RuntimeException("传入时间戳格式错误");
        }

        List<Map> dcDistributionRanges = dcDistributionRangeRepository.queryDcDistributionByTs(timestamp, PageRequest.of(0, maxNum), id);
        return dcDistributionRanges;
    }

    
}
